<?php

namespace app\controller\admin\map;

use app\model\admin\calendar\CalendarContent;
use app\model\admin\map\MapContent;
use app\model\admin\map\MapContentLabel;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\map
 */
class Content extends Backend
{
    protected $model;
    public $orderRule = [ 'id' => 'DESC'];
    protected $noNeedAuth = ['index', 'info'];
    public function initialize()
    {
        $this->model = new MapContent();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    //查看详情
    public function info()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        $info['label_id'] = implode(",", (new MapContentLabel())->where("content_id", "$id")->column("label_id"));
        return $this->success('获取成功', $info);
    }

    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $param = $this->request->param();
            if(isset($param['search_param']['label_id']['value'])&&!empty($param['search_param']['label_id']['value'])){
                $contentIds = (new MapContentLabel())->whereIn('label_id',$param['search_param']['label_id']['value'])->column("content_id");
                $where[] = [
                  'id','in',$contentIds
                ];
            }
            $limit = $this->request->param('limit', 10);
            $data = $this->model->with(['label'])->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
                $item['labelName'] = implode(",",array_column($item['label'],"name"));
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());
        try {
            $label_id = $post['label_id'];
            if (empty($label_id)) {
                return $this->error('请选择标签');
            } else {
                $label_id = explode(",", $label_id);
            }
            $data = [
                'relation_id' => $post['relation_id'],
                'title' => $post['title'],
                'img' => $post['img'],
                'deeplink_url' => $post['deeplink_url'],
                'author_name' => $post['author_name'],
                'author_img' => $post['author_img'],
                'description' => $post['description'],
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            Db::startTrans();
            $insertId = $this->model->insertGetId($data);
            if ($insertId) {
                $labelData = [];
                foreach ($label_id as $item) {
                    $labelData[] = [
                        'label_id' => $item,
                        'content_id' => $insertId,
                    ];
                }
                if (count($labelData) > 0) {
                    (new MapContentLabel())->insertAll($labelData);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = CommonFun::filterPostData($this->request->post());
        $label_id = $post['label_id'];
        if (empty($label_id)) {
            return $this->error('请选择标签');
        } else {
            $label_id = explode(",", $label_id);
        }
        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            Db::startTrans();
            $updateRes = $info->save();
            $labelData = [];
            foreach ($label_id as $item) {
                $labelData[] = [
                    'label_id' => $item,
                    'content_id' => $id,
                ];
            }
            $mapContentLabelModel = new MapContentLabel();
            $mapContentLabelModel->where("content_id",$id)->delete();
            if (count($labelData) > 0) {
                $mapContentLabelModel->insertAll($labelData);
            }
            if ($updateRes) {
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::roolback();
                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }


}